package com.junzhiit.nengji.cms.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import com.junzhiit.nengji.bo.UserBO;
import com.junzhiit.nengji.cms.service.UserService;
import com.junzhiit.nengji.cms.web.exception.HasUseException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneCodeErrorException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneCodeTimeoutException;
import com.junzhiit.nengji.cms.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.cms.web.exception.UserConfigNotFoundException;
import com.junzhiit.nengji.cms.web.exception.UserHasBindException;
import com.junzhiit.nengji.cms.web.exception.UserNotFoundException;
import com.junzhiit.nengji.cms.web.exception.VipAlreadyExistException;
import com.junzhiit.nengji.cms.web.exception.VipNotFoundException;
import com.junzhiit.nengji.cms.web.exception.shopsLocatedIntegralNotFoundException;
import com.junzhiit.nengji.cms.web.util.ViewObjectUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.SmsUtil;
import com.junzhiit.nengji.cms.web.vo.DataTablesParamVO;
import com.junzhiit.nengji.cms.web.vo.PhoneCodeVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.cms.web.vo.UserEditVO;
import com.junzhiit.nengji.cms.web.vo.UserVipVO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.ShopsLocatedIntegralDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.UserVipDAO;
import com.junzhiit.nengji.dao.VipDAO;
import com.junzhiit.nengji.dao.VipHistoryDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.cache.UserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.ShopsLocatedIntegral;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.UserVip;
import com.junzhiit.nengji.model.Vip;
import com.junzhiit.nengji.model.VipHistory;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.UserVipType;
import com.junzhiit.nengji.model.enums.VipHistoryPurchaseType;
import com.junzhiit.nengji.model.enums.VipHistoryStatus;


@Service
public class UserServiceImpl extends BaseServiceImpl implements UserService{

	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private UserCacheDAO userCacheDAO;
	
	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;
	
	@Autowired
	private ShopDAO shopDAO;
	
	@Autowired
	private UserConfigDAO userConfigDAO;
	
	@Autowired
	private ShopsLocatedIntegralDAO shopsLocatedIntegralDAO;
	
	@Autowired
	private VipDAO vipDAO;
	
	@Autowired
	private UserVipDAO userVipDAO;
	
	@Autowired
	private VipHistoryDAO vipHistoryDAO;
	
	@Override
	public Map<String, Object> findAll(DataTablesParamVO dtp, UserBO userBO) {
		List<UserBO> list = userDAO.findAll(dtp.getStart(), dtp.getLength(), userBO);
		int totalCount = userDAO.getTotalCount(userBO);
		return ViewObjectUtil.dataTables(list, dtp.getDraw(), totalCount);
	}
	
	@Override
	public ResultVO findByMobilePhone(String phone){
		ResultVO result=new ResultVO();
		User data=userDAO.findByMobilePhone(phone);
		if(data==null){
			throw new UserNotFoundException("用户未找到");
		}
		result.setData(data);
		return result;
	}
	
	
	@Override
	public ResultVO sendUserBindCode(String id){
		ResultVO result = new ResultVO();
		User user=userDAO.query(id);
		if(user==null){
			throw new UserNotFoundException("用户未找到");
		}
		
		String mobilePhone=user.getMobilePhone();
		String smsModel=SmsUtil.ALIYUN_SMS_VALIDATION;
		SmsUtil.sendPhoneCode(mobilePhone, smsModel);
		return result;
	}
	
	@Transactional
	@Override
	public ResultVO shopBindUser(@PathVariable String id,String code,String sessionId){
		ResultVO result=new ResultVO();
		
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		
		User user=userDAO.query(id);
		if(user==null){
			throw new UserNotFoundException("用户未找到");
		}
		
		if(user.getIsShop()!=null && user.getIsShop()==Is.YES.toIntValue()){
			throw new UserHasBindException("用户已被商户绑定");
		}
		
		String mobilePhone=user.getMobilePhone();
		PhoneCodeVO phoneCode = userCacheDAO.getHash(DIYKey.getMobilePhoneCodeKey(mobilePhone),
				PhoneCodeVO.class);
		// 验证码不一致
		if (!phoneCode.getCode().equals(code)) {
			throw new MobilePhoneCodeErrorException("验证码不一致");
		}
		if (phoneCode.getTimestamp() < new Date().getTime()) {
			throw new MobilePhoneCodeTimeoutException("验证码已过期");
		}
		
		int count=userDAO.findByShopIdCount(shop.getId());
		if(count==0){
			user.setIsMainPromotion(Is.YES.toIntValue());
		}
		
		user.setIsShop(Is.YES.toIntValue());
		user.setShopId(shop.getId());
		user.setBindTime(new Date());
		
		userDAO.update(user);
		return result;
	}
	
	@Override
	public ResultVO getShopBindUser(String sessionId){
		ResultVO result=new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		
		List<User> data=userDAO.findByShopId(shop.getId());
		result.setData(data);
		
		return result;
	}
	
	@Transactional
	@Override
	public ResultVO unBoundUser(String id,String sessionId,String code){
		ResultVO result=new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		
		
		User user=userDAO.query(id);
		String mobilePhone=user.getMobilePhone();
		
		PhoneCodeVO phoneCode = userCacheDAO.getHash(DIYKey.getMobilePhoneCodeKey(mobilePhone),
				PhoneCodeVO.class);
		// 验证码不一致
		if (!phoneCode.getCode().equals(code)) {
			throw new MobilePhoneCodeErrorException("验证码不一致");
		}
		if (phoneCode.getTimestamp() < new Date().getTime()) {
			throw new MobilePhoneCodeTimeoutException("验证码已过期");
		}
		
		
		User param=new User();
		param.setParentId(id);
		param.setCreatedTime(user.getBindTime());
		List<User> childrenUsers=userDAO.findByUser(param);
		
		User mainUser=userDAO.findByShopIdIsMain(shop.getId());
		for(User item:childrenUsers){
			String newFullCode=getNewFullNameByFrist(item.getFullCode(), mainUser.getCode());
			item.setFullCode(newFullCode);
			item.setParentId(mainUser.getId());
		}
		userDAO.batchUpdate(childrenUsers,true);
		
		
		user.setShopId(null);
		user.setIsShop(Is.NO.toIntValue());
		user.setBindTime(null);
		userDAO.update(user,true);
		
		
		result.setData(user);
		return result;
	}
	
	private String getNewFullNameByFrist(String fullCode, String code) {
		int beginindex = fullCode.indexOf("_") < 0 ? 0 : fullCode.indexOf("_");
		String old = fullCode.substring(0, beginindex);
		String NewFullCode = fullCode.replaceFirst(old, code);
		return NewFullCode;
	}
	
	@Transactional
	@Override
	public ResultVO edit(UserEditVO userEditVO){
		ResultVO result=new ResultVO();
		
		ShopsLocatedIntegral shopsLocatedIntegral=shopsLocatedIntegralDAO.query(userEditVO.getShopLocatedIntegralId());
		
		if(shopsLocatedIntegral==null){
			throw new shopsLocatedIntegralNotFoundException("入驻积分未找到");
		}
		
		if(shopsLocatedIntegral.getStatus()==Is.YES.toIntValue()){
			throw new HasUseException("已返回积分");
		}
		
		User user=userDAO.query(shopsLocatedIntegral.getInviterId());
		if(user==null){
			throw new UserNotFoundException("用户未找到");
		}
		
		UserConfig userConfig=userConfigDAO.getUserConfig(user.getId());
		
		if(userConfig==null){
			throw new UserConfigNotFoundException("用户配置未找到");
		}
		
		Double returnIntegral=shopsLocatedIntegral.getReturnIntegral();
		
		switch (userEditVO.getType()) {
			case 0:
				double pileMoney=userConfig.getPileMoney();
				double currentMoney=userConfig.getCurrentMoney();
				
				userConfig.setPileMoney(pileMoney+returnIntegral);
				userConfig.setCurrentMoney(currentMoney+returnIntegral);
				
				break;
			case 1:
				double WithdrawalMoney=userConfig.getWithdrawalMoney();
				userConfig.setWithdrawalMoney(WithdrawalMoney+returnIntegral);
				break;
			case 2:
				double pileLegeIntegral=userConfig.getPileLegeIntegral();
				double legeIntegral=userConfig.getLegeIntegral();
				
				userConfig.setPileLegeIntegral(pileLegeIntegral+returnIntegral);
				userConfig.setLegeIntegral(legeIntegral+returnIntegral);
				break;
			default:
				break;
		}
		
		userConfigDAO.update(userConfig);
		
		shopsLocatedIntegral.setReturnType(userEditVO.getType());
		shopsLocatedIntegral.setStatus(Is.YES.toIntValue());
		shopsLocatedIntegralDAO.update(shopsLocatedIntegral);
		
		result.setData(userConfig);
		return result;
	}
	
	@Override
	public ResultVO updateUserIdentity(UserVipVO userVipVO) {
		ResultVO result=new ResultVO();
		
		//查找设置的身份信息
		Vip vip = vipDAO.query(userVipVO.getVipId());
		if(vip==null){
			throw new VipNotFoundException("身份标签不存在");
		}
		//修改该用户正在使用的身份状态
		UserVip identity = userVipDAO.checkUserVip(userVipVO.getUserId());
		if(identity != null){
			if(identity.getVipId().equals(vip.getId())){
				throw new VipAlreadyExistException("该用户已经设置该身份，请勿重复设置！");
			}
			identity.setIsUse(Is.NO.toIntValue());
			userVipDAO.update(identity);
		}
		
		//插入用户身份表
		UserVip userVip = new UserVip();
		userVip.setUserId(userVipVO.getUserId());
		userVip.setVipId(userVipVO.getVipId());
		userVip.setIsUse(Is.YES.toIntValue());
		userVip.setType(UserVipType.PRESENT.toIntType());
		userVip.setName(userVipVO.getName());
		userVip.setMobilePhone(userVipVO.getMobilePhone());
		userVipDAO.insert(userVip);
		
		//如果赠送积分，更新user_config
		if(userVipVO.getIsPresent()!=null && userVipVO.getIsPresent()==Is.YES.toIntValue()){
			UserConfig userConfig = userConfigDAO.getUserConfig(userVipVO.getUserId());
			if(userConfig==null){
				throw new UserConfigNotFoundException("用户配置信息不存在");
			}
			userConfig.setPileMoney(userConfig.getPileMoney() + userVipVO.getPresentIntegral());
			userConfig.setCurrentMoney(userConfig.getCurrentMoney() + userVipVO.getPresentIntegral());
			userConfigDAO.update(userConfig);
		}
		
		//插入身份变更历史表vip_history
		VipHistory vipHistory=new VipHistory();
		vipHistory.setUserId(userVipVO.getUserId());
		vipHistory.setVipId(userVipVO.getVipId());
		vipHistory.setPurchaseType(VipHistoryPurchaseType.PRESENT.toIntStatus());
		vipHistory.setStatus(VipHistoryStatus.NONEED.toIntStatus());
		vipHistory.setIsPresent(userVipVO.getIsPresent());
		vipHistory.setPresentIntegral(userVipVO.getPresentIntegral());
		vipHistoryDAO.insert(vipHistory);
		
		//更新user表的真实姓名和联系方式
		User user=userDAO.query(userVipVO.getUserId());
		if(user==null){
			throw new UserNotFoundException("用户不存在");
		}
		user.setName(userVipVO.getName());
		user.setMobilePhone(userVipVO.getMobilePhone());
		userDAO.update(user);
		
		return result;
	}
}
